package chances.epg.ui.taglib.utils;

import java.util.Collection;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

@SuppressWarnings("serial")
public class IndexTag extends TagSupport {
	private String var;
	private String expr;
	private Object collection;
	private int defaultIndex = 0;

	@SuppressWarnings("rawtypes")
	public int doEndTag() throws JspException {
		int index = defaultIndex;
		ExpressionParser parser = new SpelExpressionParser();
		Expression exp = parser.parseExpression(expr);
		if (Collection.class.isInstance(collection)) {
			Object[] arrObjs = ((Collection) collection).toArray();
			for (int i = 0; i < arrObjs.length; i++) {
				EvaluationContext context = new StandardEvaluationContext(arrObjs[i]);
				Boolean c = exp.getValue(context, Boolean.class);
				if (c) {
					index = i;
					break;
				}
			}
		}
		pageContext.setAttribute(this.var, index);
		this.release();
		return super.doEndTag();
	}

	@Override
	public void release() {
		super.release();
		this.var = null;
		this.expr = null;
		this.collection = null;
		this.defaultIndex = 0;
	}

	public String getVar() {
		return var;
	}

	public String getExpr() {
		return expr;
	}

	public void setVar(String var) {
		this.var = var;
	}

	public void setExpr(String expr) {
		this.expr = expr;
	}

	public Object getCollection() {
		return collection;
	}

	public void setCollection(Object collection) {
		this.collection = collection;
	}

}
